package com.leaves.auth.service.impl;

import com.leaves.auth.common.utils.IsNotEmptyUtil;
import com.leaves.auth.common.utils.MD5Util;
import com.leaves.auth.config.reids.JedisUtil;
import com.leaves.auth.entity.TUser;
import com.leaves.auth.jwt.JwtUtil;
import com.leaves.auth.mapper.TRoleMapper;
import com.leaves.auth.mapper.TUserMapper;
import com.leaves.auth.response.ResponseData;
import com.leaves.auth.response.ResponseDataUtil;
import com.leaves.auth.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LEAVES
 * @Date: 2020年12月30日 13时44分45秒
 * @Version 1.0
 * @Description:
 */
@Service
@Slf4j
public class UserService implements IUserService {

    @Resource
    private TUserMapper userMapper;
    @Resource
    private TRoleMapper roleMapper;

    /**
     * 根据用户名查询用户信息（程序内部调用）
     * @param username
     * @return
     */
    @Override
    public TUser getUserByUserName(String username) {
        TUser tUser = userMapper.selectByUserName(username);
        log.info("权限认证===>根据用户名查询用户信息：" + tUser.toString());
        return tUser;
    }

    /**
     * 登录实现
     * @param username
     * @param password
     * @param response
     * @return
     */
    @Override
    public ResponseData login(String username, String password, HttpServletResponse response) {
        log.info("用户登录");
        TUser tUser = userMapper.selectUserToRoleByUserName(username);
//        Set<String> roleByUserName = tRoleService.getRoleByUserName(username);
        //由于前端+controller两处对username和password进行了判断，所以此处不再做判断
        if (tUser != null) {
            //解密数据库中用户密码
            String dbpwd = MD5Util.convertMD5(tUser.getPassword());
            //判断输入的用户名和密码是否与数据库中的用户名、密码一致
            if(tUser.getUsername().equals(username) && dbpwd.equals(password)){
                //生成token
                String token = JwtUtil.sign(tUser.getUsername());
                log.info("登录时生成的token = " + token);
                //获取当前时间的时间戳
                long currentTimeMillis = System.currentTimeMillis();
                //向redis中存入token
                JedisUtil.setJson(username, token, JwtUtil.REFRESH_EXPIRE_TIME);
                //向前端返回token
                HttpServletResponse httpServletResponse = response;
                httpServletResponse.setHeader("token", token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", "token");
                log.info("登录成功：" + tUser.toString());
                tUser.setPassword(dbpwd);
                Map<String, Object> map = new HashMap<>();
                map.put("user", tUser);
                map.put("token", token);
                return ResponseDataUtil.success("登录成功", map);
            }
            return ResponseDataUtil.fail("登录失败，用户名或密码错误！");
        }
        return ResponseDataUtil.fail("登录失败，用户不存在！");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @Override
    public ResponseData logout(HttpServletRequest request) {
        log.info("退出登录");
        //获取token
        String token = request.getHeader("Authorization");
        //去掉token前缀
        token = token.substring(7);
        //token非空判断
        if (IsNotEmptyUtil.isEmpty(token)) {
            return ResponseDataUtil.fail("无效的token！");
        }
        //获取token中的用户名
        String username = JwtUtil.getAccount(token);
        //判断该token的用户是否存在
        TUser tUser = userMapper.selectByUserName(username);
        if (tUser != null) {
            log.info(" 用户名: " + username + " 退出登录成功！ ");
            if (JedisUtil.getJson(username) == null){
                return ResponseDataUtil.fail("已经退出登录过了！");
            }
            //清空redis中用户Token缓存
            Long aLong = JedisUtil.delKey(username);
            return ResponseDataUtil.success("退出登录成功！");
        }
        return ResponseDataUtil.fail("令牌失效，请重新登录！");
    }

    /**
     * 查询全部用户信息
     * @return
     */
    @Override
    public ResponseData queryUserList() {
        List<TUser> tUsers = userMapper.selectAll();
        if (!tUsers.isEmpty()){
            for (TUser tUser : tUsers){
                //密码解密
                tUser.setPassword(MD5Util.convertMD5(tUser.getPassword()));
            }
            log.info("获取全部用户信息：" + tUsers.toString());
            return ResponseDataUtil.success("查询成功！", tUsers);
        }
        return ResponseDataUtil.fail("暂无用户信息！");
    }

    /**
     * 根据用户查询用户信息（接口）
     * @param username
     * @return
     */
    @Override
    public ResponseData queryUserByUserName(String username) {
        TUser tUser = userMapper.selectByUserName(username);
        if (tUser != null){
            return ResponseDataUtil.success("查询成功！", tUser);
        }
        return ResponseDataUtil.fail("暂无该用户信息！");
    }
}
